package com.easy.service.impl;

import com.easy.bean.Favorites;
import com.easy.bean.User;
import com.easy.mapper.FavoritesDao;
import com.easy.mapper.UserDao;
import com.easy.service.FavoritesService;
import com.easy.service.UserService;
import com.easy.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class FavoritesServiceImpl implements FavoritesService {

    private static final String CACHE_NAME = "favorite";

    @Autowired
    FavoritesDao favoritesDao;

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'favorite:' + #p0.id", condition = "#result != null")
    public Favorites add(Favorites favorites) {
        // 先查询是否已存在相同用户和景点的记录（包括软删除的记录）
        Favorites existingFavorite = favoritesDao.findByUserAndAttraction(
                favorites.getUser_id(), favorites.getAttraction_id());

        // 如果已存在，直接返回该记录
        if (existingFavorite != null) {
            // 如果是软删除状态，恢复它
            if (existingFavorite.getIs_deleted() == 1) {
                favoritesDao.edit(existingFavorite);
            }
            return existingFavorite;
        }

        // 新增数据
        favoritesDao.add(favorites);
        // 通过主键查询数据库的数据
        Favorites result = favoritesDao.one(favorites.getId());
        return result;
    }

    @Override
   @CacheEvict(value = CACHE_NAME, key = "'favorite:id:' + #p0")
    public int del(Integer id) {
        return favoritesDao.del(id);
    }

    @Override
    @CacheEvict(value = CACHE_NAME, key = "'favorite:' + #p0.id", condition = "#p0 != null and #p0.id != null")
    public Favorites edit(Favorites favorites) {
        favoritesDao.edit(favorites);
        Favorites result = favoritesDao.one(favorites.getId());
        return result;
    }

    @Override
   @Cacheable(value = CACHE_NAME, key = "'favorite:list:' + T(java.util.Objects).hash(#p0)", unless = "#result == null or #result.isEmpty()")
    public List<Favorites> all(Favorites favorites) {
        return favoritesDao.all(favorites);
    }

    @Override
   @Cacheable(value = CACHE_NAME, key = "'favorite:id:' + #p0", unless = "#result == null")
    public Favorites one(Integer id) {
        System.out.println("从数据库查询收藏信息，ID: " + id);
        return favoritesDao.one(id);
    }

    @Override
    public void page(Page page, Favorites favorites) {
        int count = favoritesDao.pageCount(favorites);
        Object data = favoritesDao.page(page, favorites);
        page.setCount(count);
        page.setData(data);
    }

}
